//
//  WTOGoodsListTabBarView.m
//  WolianwPro
//
//  Created by lishuaiWLW on 16/11/30.
//  Copyright © 2016年 我连网. All rights reserved.
//

#import "WTOGoodsListTabBarView.h"
#import "WTOGoodsListTabbarOverlayView.h"
#import "WTOShoppingCarCell.h"
#import "WTOShoppingCarSectionHeaderView.h"
#import "WTOShopCarCacheData.h"

#define SECTION_HEIGHT 30.0
#define ROW_HEIGHT 50.0

@interface WTOGoodsListTabBarView ()<UITableViewDelegate,UITableViewDataSource,WTOShoppingCarSectionHeaderViewDelegate>

@property (nonatomic,strong) WTOGoodsListTabbarOverlayView *overlayView;//弹出tableview的时候的蒙版

@property (nonatomic,strong) UILabel *money; //中间的金额提示label

@property (nonatomic,strong) UIButton *accountBtn;//结算按钮

@property (nonatomic,assign) NSInteger nTotal;//总金额 用于判断够不够最低消费 还差多少才够

@property (nonatomic,strong) NSMutableArray *objects;//已经选择的商品的数据源

@property (nonatomic,strong) UIView *marginLine;//金额和配送费的竖分割线

@property (nonatomic,strong) UILabel *mealsFeeLabel;//餐盒费

@property (nonatomic,strong) UILabel *shippingFeeLabel;//配送费

@property (nonatomic,strong)NSMutableArray *dataSource;//数据源

@property (nonatomic,copy)NSArray *promotionArray;//促销数据源

@property (nonatomic,strong)WTOShoppingCarSectionHeaderView *headView;//头部视图


@end

@implementation WTOGoodsListTabBarView

-(instancetype) initWithFrame:(CGRect)frame inView:(UIView *)parentView
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.parentView = parentView;
        self.dataSource = [[NSMutableArray alloc] init];
        [self layoutUI];
    }
    
    return self;
}

-(void)layoutUI
{
    
    //横线
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 0.5)];
    line.backgroundColor = LTXDefaultsLineColor;
    [self addSubview:line];
    
    //购物金额提示框
    _money = [[UILabel alloc] initWithFrame:CGRectMake(70, 15, 75, 20)];
    [_money setTextColor:ZQColor(153, 153, 153)];
    [_money setText:@"￥0"];
    [_money setFont:[UIFont boldSystemFontOfSize:16]];
    [_money sizeToFit];
    [self addSubview:_money];
    
    //结账按钮
    _accountBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _accountBtn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    _accountBtn.frame = CGRectMake(self.bounds.size.width - 110, 0, 110, 50);
    _accountBtn.backgroundColor = ZQColor(255, 78, 61);
    [_accountBtn addTarget:self action:@selector(pay:) forControlEvents:UIControlEventTouchUpInside];
    _accountBtn.enabled = NO;
    [self addSubview:_accountBtn];
    
    //购物车
    _shoppingCartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shoppingCartBtn setUserInteractionEnabled:NO];
    [_shoppingCartBtn setBackgroundImage:[UIImage imageNamed:@"order_car_grey"] forState:UIControlStateNormal];
    _shoppingCartBtn.frame = CGRectMake(10, -15, 50, 50);
    [_shoppingCartBtn addTarget:self action:@selector(clickCartBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_shoppingCartBtn];
    
    //餐盒费 配送费  和总金额的分割线
    UIView *marginView = [[UIView alloc]init];
    
    marginView.backgroundColor = ZQColor(228, 228, 228);
    
    marginView.frame = CGRectMake(CGRectGetMaxX(_money.frame) + 5, 10, 0.5, self.frame.size.height - 20);
    
    [self addSubview:marginView];
    self.marginLine = marginView;
    self.marginLine.hidden = YES;
    
    //餐盒费
    CGFloat mealsFeeLabelW = self.width - CGRectGetMaxX(marginView.frame) - 5 - 100;
    _mealsFeeLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(marginView.frame) + 5, 10, mealsFeeLabelW, 0)];
    
    _mealsFeeLabel.font = [UIFont systemFontOfSize:13];
    _mealsFeeLabel.textColor = ZQColor(153, 153, 153);
    
    [_mealsFeeLabel sizeToFit];
    _mealsFeeLabel.hidden = YES;
    [self addSubview:_mealsFeeLabel];
    
    //配送费
    _shippingFeeLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(marginView.frame) + 5, CGRectGetMidY(marginView.frame), mealsFeeLabelW, 0)];
    
    
    _shippingFeeLabel.font = [UIFont systemFontOfSize:13];
    _shippingFeeLabel.textColor = ZQColor(153, 153, 153);
    _shippingFeeLabel.hidden = YES;
    [_shippingFeeLabel sizeToFit];
    
    [self addSubview:_shippingFeeLabel];
    
    //红点提示
    if (!_badge) {
        _badge = [[WTOShoppingCarBadgeView alloc] initWithFrame:CGRectMake(_shoppingCartBtn.frame.size.width - 15 -3, 2, 20, 20) withString:nil];
        [_shoppingCartBtn addSubview:_badge];
    }
    
    //最大的高度
    int maxHeight = self.parentView.frame.size.height - 250 - 30;
    
    //创建蒙版
    _overlayView = [[WTOGoodsListTabbarOverlayView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _overlayView.ShoppingCartView = self;
    [_overlayView addSubview:self];
    [self.parentView addSubview:_overlayView];
    
    //创建表
    if (self.orderList == nil) {
        
        UITableView *orderlist = [[UITableView alloc] initWithFrame:CGRectMake(0,self.parentView.bounds.size.height - maxHeight, self.bounds.size.width, maxHeight) style:UITableViewStylePlain];
        orderlist.delegate = self;
        orderlist.dataSource = self;
        orderlist.rowHeight = 60;
        orderlist.sectionHeaderHeight = 30;
        [orderlist registerClass:[WTOShoppingCarCell class] forCellReuseIdentifier:kCellIdentifier_shopCar];
        orderlist.showsHorizontalScrollIndicator = NO;
        orderlist.showsVerticalScrollIndicator = NO;
        orderlist.backgroundColor = [UIColor whiteColor];
        [_overlayView addSubview:orderlist];
        self.orderList = orderlist;
    }
    
    //模板默认是透明的
    _overlayView.alpha = 0.0;
    
    //默认是收起的
    _up = NO;
    
}

- (void)setPayBtnString:(NSString *)payBtnString
{
    _payBtnString = payBtnString;
    
    [_accountBtn setTitle:payBtnString forState:UIControlStateNormal];
}

#pragma mark - publickMethods

//在内存获取总数量
-(long)getBuyCountFromShopCarDataSource
{
    long count = 0;
    
    for (MQLFoodModel *entity in self.dataSource)
    {
        count += entity.buyCount;
    }
    return count;
}

#pragma mark - other

//数据源有变动的情况下刷新购物车
-(void)refreshShopCar
{
    [self refreshCartImage];
    
    [self setBadgeWithNum:[NSString stringWithFormat:@"%ld",(long)[self getBuyCarNum]]];
    
    [self refreshList];
    
    [self calculateOrderFareAndSetTotolMoney];
    
    [self refreshSectionHeaderBuyCount];
}

//刷新头部sectionheader
-(void)refreshSectionHeaderBuyCount
{
    self.headView.foodCount = [self getBuyCarNum];
}

//设置购买数量，角标
-(void)setBadgeWithNum:(NSString *)numString
{
    self.badge.badgeValue = numString;
}

//设置购物车数据源
-(void)setShopCarDataSourceWithArray:(NSArray *)array
{
    [self.dataSource removeAllObjects];
    
    [self.dataSource addObjectsFromArray:array];
}

//刷新表格
-(void)refreshList
{
    [self.orderList reloadData];
}

//计算并设置总价，餐盒费，配送费并设置
-(void)calculateOrderFareAndSetTotolMoney
{
    double totalPrice = 0.0f;
    double boxFare = 0.0f;
    double goodsPrice = 0.0f;
    
    for (MQLFoodModel *detailEntity in self.dataSource) {

        double fare = 0.0f;


        goodsPrice += (detailEntity.price * detailEntity.buyCount);
        boxFare += fare;
    }
    
    //总价
    totalPrice = goodsPrice;
    
    [self setTotalMoney:totalPrice shippingFare:self.shoppingFare mealBoxFare:boxFare];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(caculateMoney:)]) {
        [self.delegate caculateMoney:totalPrice];
    }
    
}

//获取购物车总金额
-(double)getTotalPrice
{
    double totalPrice = 0.0f;
    double boxFare = 0.0f;
    double goodsPrice = 0.0f;
    

    for (MQLFoodModel *detailEntity in self.dataSource) {

        double fare = 0.0f;

        goodsPrice += (detailEntity.price * detailEntity.buyCount);
        boxFare += fare;
    }
    
    //总价
    totalPrice = goodsPrice;
    
    return totalPrice;
}

//获取购物车数据源
-(NSArray *)getShopCarDataSource
{
    return [self.dataSource copy];
}

//添加模型到购物车
-(void)addFoodModelToShopCar:(MQLFoodModel *)model
{
    if (![self.dataSource containsObject:model]) {
        
        [self.dataSource addObject:model];
    }
    [self refreshShopCar];
}
//从购物车移除模型
-(void)removeFoodModelAtShopCar:(MQLFoodModel *)model
{
    if ([self.dataSource containsObject:model] && !model.buyCount) {
        
        [self.dataSource removeObject:model];
    }
    [self refreshShopCar];
}

//获取列表对象
-(UITableView *)getShopCarTableView
{
    return self.orderList;
}

//刷新frame
-(void)updateFrame
{
    
    float height = 0;
    NSUInteger nRow = 0;
    nRow = [self.dataSource count];
    
    height = nRow * ROW_HEIGHT + SECTION_HEIGHT;
    
    int maxHeight = self.parentView.frame.size.height - 250 - 30;
    
    if (height >= maxHeight) {
        height = maxHeight;
    }
    
    //初始Y
    float orignY = self.orderList.frame.origin.y;
    
    self.orderList.frame = CGRectMake(self.orderList.frame.origin.x, self.parentView.bounds.size.height - height - 50 - SafeAreaBottomHeight - 44, self.orderList.frame.size.width, height);
    
    //排序后Y
    float currentY = self.orderList.frame.origin.y;
    
    if (_up) {
        
        [UIView animateWithDuration:0.5 animations:^{
            CGPoint point = self.shoppingCartBtn.center;
            
            point.y -= orignY - currentY;
            
            [self.shoppingCartBtn setCenter:point];
            
            
        } completion:^(BOOL finished) {
            
            
        }];
    }
    
}

#pragma mark - private method

//清空购物车
-(void)clearnShopCar
{
    //清空购物车商品的购买个数
    [self clearnBuyAmmount];
    
    //清空数据源
    [self.dataSource removeAllObjects];
    
    //设置购买数量
    self.badge.badgeValue = [NSString stringWithFormat:@"%zd",[self getBuyCarNum]];
    
    //计算订单金额,并刷新总金额
    [self calculateOrderFareAndSetTotolMoney];
    
    //设置购物车的图标
    [self refreshCartImage];
    
    //收回购物车
    if (self.up)
    {
        [self dismissAnimated:YES];
    }
    
    //刷新列表
    [self refreshList];
    
}

//获取购物车商品总数
- (NSInteger)getBuyCarNum
{
    NSInteger totalNum = 0;
    for (MQLFoodModel *foodmodel in self.dataSource) {
        totalNum += foodmodel.buyCount;
    }
    return totalNum;
}

//设置购物车图片
- (void)refreshCartImage
{
    if (self.dataSource.count>0) {
        [self setCartImage:@"order_car"];
    }else {
        [self setCartImage:@"order_car_grey"];
    }
}

//清空购买个数
-(void)clearnBuyAmmount
{
    for (MQLFoodModel *model in self.dataSource) {
        model.buyCount = 0;
    }
}

//设置总金额
-(void)setTotalMoney:(CGFloat)nTotal shippingFare:(float)shippingFare mealBoxFare:(float)boxFare
{
    _nTotal = nTotal;
    
    NSString *amount = [NSString stringWithFormat:@"%.02f",nTotal];
    
    if(nTotal > 0)
    {
        _money.font = [UIFont boldSystemFontOfSize:16.0f];
        _money.textColor = ZQColor(255, 60, 41);
        _money.text = [NSString stringWithFormat:@"$%@",amount];
        [_money sizeToFit];
        float value = _minFreeMoney - nTotal;
        
        if (![_payBtnString isEqualToString:@"暂停接待"])
        {
            
            if (value > 0.001) {
                
                _accountBtn.enabled = NO;
                [_accountBtn setTitle:[NSString stringWithFormat:@"还差$%0.02f",value] forState:UIControlStateNormal];
                [_accountBtn setBackgroundColor:ZQColor(255, 78, 61)];
            }
            else
            {
                _accountBtn.enabled = YES;
                [_accountBtn setTitle:@"去结算" forState:UIControlStateNormal];
                [_accountBtn setBackgroundColor:ZQColor(255, 78, 61)];
                
            }
            
        }
        [_shoppingCartBtn setUserInteractionEnabled:YES];
    }
    else
    {
        if (![_payBtnString isEqualToString:@"暂停接待"])
        {
            [_accountBtn setTitle:[NSString stringWithFormat:@"还差$%.02f",_minFreeMoney] forState:UIControlStateNormal];
        }
        [_money setTextColor:ZQColor(153, 153, 153)];
        [_money setText:@"$0"];
        [_money setFont:[UIFont boldSystemFontOfSize:16]];
        [_money sizeToFit];
        _accountBtn.enabled = NO;
        [_accountBtn setBackgroundColor:ZQColor(210, 210, 210)];
        [_shoppingCartBtn setUserInteractionEnabled:NO];
    }
    
    if (boxFare > 0 || shippingFare>0) {
        
        self.marginLine.hidden = NO;
        self.marginLine.x = CGRectGetMaxX(_money.frame) + 5;
    } else
    {
        self.marginLine.hidden = YES;
    }
    
    if (shippingFare > 0){
        
        if (self.sendType == 1004)
        {
            _shippingFeeLabel.text = [NSString stringWithFormat:@"配送费以订单为准"];
        }else
        {
            _shippingFeeLabel.text = [NSString stringWithFormat:@"配送费:%.02f",shippingFare];
        }
        [_shippingFeeLabel sizeToFit];
        _shippingFeeLabel.x = CGRectGetMaxX(self.marginLine.frame) + 5;
        _shippingFeeLabel.width = self.width - CGRectGetMaxX(self.marginLine.frame) - 5 - 100;
        _shippingFeeLabel.hidden = NO;
        
    } else
    {
        _shippingFeeLabel.hidden = YES;
    }
    
    if (boxFare > 0) {
        
        _mealsFeeLabel.text = [NSString stringWithFormat:@"餐盒费:%.02f",boxFare];
        [_mealsFeeLabel sizeToFit];
        _mealsFeeLabel.x = CGRectGetMaxX(self.marginLine.frame) + 5;
        _mealsFeeLabel.width = self.width - CGRectGetMaxX(self.marginLine.frame) - 5 - 100;
        _mealsFeeLabel.hidden = NO;
        
    }else{
        _mealsFeeLabel.hidden = YES;
    }
    
    if (_shippingFeeLabel.hidden && !_mealsFeeLabel.hidden) {
    
        _mealsFeeLabel.y = 20;
    }else
    {
        _mealsFeeLabel.y = 10;
    }
    
    if (_mealsFeeLabel.hidden && !_shippingFeeLabel.hidden)
    {
        _shippingFeeLabel.y = 20;
        
    }else
    {
        _shippingFeeLabel.y = CGRectGetMidY(self.marginLine.frame);
    }
    
}

//设置购物车标识
-(void)setCartImage:(NSString *)imageName
{
    [_shoppingCartBtn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}

//点击购物车按钮
-(void)clickCartBtn:(UIButton *)sender
{
    
    if (![_badge.badgeValue intValue]) {
        [_shoppingCartBtn setUserInteractionEnabled:NO];
        return;
    }
    
    [self updateFrame];
    
    [_overlayView addSubview:self.orderList];
    
    [UIView animateWithDuration:0.5 animations:^{
        CGPoint point = self.shoppingCartBtn.center;
        CGPoint labelPoint = self.money.center;
        
        point.y -= (self.orderList.frame.size.height + 50);
        labelPoint.x -= 60;
        self.overlayView.alpha = 1.0;
        
        [self.shoppingCartBtn setCenter:point];
        [self.money setCenter:labelPoint];
        self.marginLine.x = CGRectGetMaxX(self.money.frame) + 5;
        self.mealsFeeLabel.x = CGRectGetMaxX(self.marginLine.frame) + 5;
        self.mealsFeeLabel.width = self.width - CGRectGetMaxX(self.marginLine.frame) - 5 - 100;
        self.shippingFeeLabel.x = CGRectGetMaxX(self.marginLine.frame) + 5;
        self.shippingFeeLabel.width = self.width - CGRectGetMaxX(self.marginLine.frame) - 5 - 100;
        
    } completion:^(BOOL finished) {
        
        self.up = YES;
    }];
}

#pragma mark - 小黄条
#pragma mark - PromotionPriceCaculate


#pragma mark - dismiss
-(void)dismissAnimated:(BOOL)animated
{
    
    [_shoppingCartBtn bringSubviewToFront:self.overlayView];
    [UIView animateWithDuration:0.5 animations:^{
        
        CGPoint point = self.shoppingCartBtn.center;
        CGPoint labelPoint = self.money.center;
        
        point.y += (self.orderList.frame.size.height + 50);
        labelPoint.x += 60;
        self.overlayView.alpha = 0.0;
        [self.shoppingCartBtn setCenter:point];
        [self.money setCenter:labelPoint];
        self.marginLine.x = CGRectGetMaxX(self.money.frame) + 5;
        self.mealsFeeLabel.x = CGRectGetMaxX(self.marginLine.frame) + 5;
        self.mealsFeeLabel.width = self.width - CGRectGetMaxX(self.marginLine.frame) - 5 - 100;
        self.shippingFeeLabel.x = CGRectGetMaxX(self.marginLine.frame) + 5;
        self.shippingFeeLabel.width = self.width - CGRectGetMaxX(self.marginLine.frame) - 5 - 100;
        
    } completion:^(BOOL finished) {
        
        self.up = NO;
    }];
}

//点击支付
-(void)pay:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(clickPay:)]) {
        [self.delegate clickPay:sender];
    }
}
#pragma mark - UITableViewDataSource and Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WTOShoppingCarCell *cell = (WTOShoppingCarCell *)[tableView dequeueReusableCellWithIdentifier:kCellIdentifier_shopCar forIndexPath:indexPath];
    MQLFoodModel *model = self.dataSource[indexPath.row];

    cell.model = model;
    
    WS(weakSelf);
    
    cell.operationBlock = ^(NSUInteger nCount,BOOL plus, NSString *goodsID) {
        
        if (plus) {
            

            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(addGoodsCount:withModel:withIndexPath:)]) {

                [weakSelf.delegate addGoodsCount:weakSelf withModel:model withIndexPath:indexPath];
            }
            [weakSelf.orderList reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
        }else {//点击购物车对应商品减号按钮的情况
            
            
            if (model.buyCount == 0)
            {

                [weakSelf.dataSource removeObject:model];
                [weakSelf updateFrame];


                if ([weakSelf getBuyCarNum]==0) {//如果购物车只添加了这一个商品那么移除该商品后购物车中没有商品则表格下降隐藏
                    [weakSelf dismissAnimated:YES];
                }
                [tableView reloadData];

            } else {

                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }
            
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(reduceGoodsCount:withModel:withIndexPath:)]) {
                
                [weakSelf.delegate reduceGoodsCount:weakSelf withModel:model withIndexPath:indexPath];
            }
        }
        
        [weakSelf refreshShopCar];

    };
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (!self.headView) {
        self.headView = [[WTOShoppingCarSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 30)];
        
        self.headView.delegate = self;
    }
    self.headView.foodCount = [self getBuyCarNum];
    return self.headView;
}

#pragma mark - WTOShoppingCarHeadDelegate
-(void)clickClearShoppingBtnWithShoppingCarSectionHeaderView:(WTOShoppingCarSectionHeaderView *)view clearBtn:(UIButton *)clearBtn
{
    
    //清空购物车
    [self clearnShopCar];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(clearnShopCar)]) {
        
        [self.delegate clearnShopCar];
    }

}

#pragma mark - getter and setter

@end
